package com.hujf.netty.codec;

import com.hujf.netty.codec.pojo.MyDataInfo;
import com.hujf.netty.codec.pojo.StudentPOJO;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @author Hujf
 * @title: SimpleHandlerForClient
 * @date 2021/1/28 0028下午 2:16
 * @description: TODO
 */
public class SimpleHandlerForClient extends ChannelInboundHandlerAdapter {
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
       cause.printStackTrace();
        ctx.close();
    }

    //1.
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
       //发送一个student对象到服务器
        MyDataInfo.MyMessage message = MyDataInfo.MyMessage.newBuilder().setDataType(MyDataInfo.MyMessage.DataType.StudentType).setStudent(MyDataInfo.Student.newBuilder().setId(4).setName("hujf").build()).build();
        ctx.writeAndFlush(message);
    }

    //3.
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf =(ByteBuf)msg;
        System.out.println("收到来自服务器的消息 "+byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println(ctx.channel().remoteAddress());
    }

}
